#define _GNU_SOURCE
#include "app_bluetooth.h"
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include "app_message.h"
#include <assert.h>
#include "log/log.h"

/**
 * 等待获取蓝牙接收到ack数据（OK\r\n）
 */
static int wait_ack(Device *device)
{
    // 等待一定的时间
    usleep(1000 * 50);
    char buf[4];
    read(device->fd, buf, 4);
    if (memcmp(buf, "OK\r\n", 4) == 0)
    {
        return 0;
    }
    else
    {
        return -1;
    }
}
/**
 * 测试蓝牙是否可用
 */
int app_bluetooth_status(Device *device)
{
    write(device->fd, "AT\r\n", 4); 
    return wait_ack(device);
}
/**
 * 修改蓝牙名称
 */
int app_bluetooth_rename(Device *device, char *name)
{
    write(device->fd, "AT+NAME", 7);
    write(device->fd, name, strlen(name));
    write(device->fd, "\r\n", 2);
    return wait_ack(device);
}
/**
 * 设置蓝牙波特率
 */
int app_bluetooth_setBraudRate(Device *device, BTBraudRate baud_rate)
{
    write(device->fd, "AT+BAUD", 7);
    write(device->fd, baud_rate, 1);
    write(device->fd, "\r\n", 2);
    return wait_ack(device);
}
/**
 * 重启蓝牙
 */
int app_bluetooth_reset(Device *device)
{
    write(device->fd, "AT+RESET\r\n", 10);
    return wait_ack(device);
}
/**
 * 设置蓝牙网络ID
 */
int app_bluetooth_setNetID(Device *device, char *net_id)
{
    write(device->fd, "AT+NETID", 8);
    write(device->fd, net_id, strlen(net_id));
    write(device->fd, "\r\n", 2);
    return wait_ack(device);
}
/**
 * 设置蓝牙MAC地址
 */
int app_bluetooth_setMaddr(Device *device, char *maddr)
{
    write(device->fd, "AT+MADDR", 8);
    write(device->fd, maddr, strlen(maddr));
    write(device->fd, "\r\n", 2);
    return wait_ack(device);
}
/**
 * 处理读取的蓝牙数据的函数
 */
int app_bluetooth_postRead(Device *device, char *data, int len)
{

    return 0;
}
/**
 * 处理将要写入蓝牙数据的函数
 */
int app_bluetooth_preWrite(Device *device, char *data, int len)
{

    return 0;
}